#!/usr/bin/env python
'''
Functions and classes that handles the tools
'''

import Breweries
import Coasters
import Gui
import Img

from DB import *
from GladeWidgets import GladeWidget

def on_btnExport_clicked(wnd, event):
    '''Export everything to HTML'''
    print "begin the export"

    # TODO: a lot of things!
    # - choose dir where to export the files
    # - give a style customization option
    # - convert strings to unicode html rapresentation

    dir = "html/"
    db = DB()

    head = file("head.tmpl")
    footer = file("footer.tmpl")

    nf = open(dir + "index.html", "w")
    for line in head:
        nf.write(line)

    index = 0
    brands = db.getAllBrands()
    for name in brands:
        brewery = db.getBreweryByBrand(name[0]).encode("utf-8")
        string = "<h2>" + str(name[0]) + ", brewed by " + brewery + "</h2>\n"
        nf.write(string)

        print "exporting " + name[0] + "..."
        coasters = db.getAllCoasters(name[0])
        for id, brand in coasters:
            img_front = dir + "img/" + str(index) + "_front.jpg"
            img_back = dir + "img/" + str(index) + "_back.jpg"
            writeImageToDisk(db.getFrontCoasterImg(id), img_front)
            writeImageToDisk(db.getBackCoasterImg(id), img_back)

            nf.write("<img src=\"img/" + str(index) + "_front.jpg\" alt=\"\" /> ")
            nf.write("<img src=\"img/" + str(index) + "_back.jpg\" alt=\"\" />")
            nf.write("<br />\n")
            index = index + 1

    for line in footer:
        nf.write(line)

    
def writeImageToDisk(img, out):
    '''Write a raw stream of data (coaster image) to disk'''
    pixbuf = Img.convertRawStreamToPixbuf(img)
    pixbuf.save(out, "jpeg", {"quality": "85"})


if __name__ == '__main__':
    on_btnExport_clicked(None, None)
